package fyp.spedmew;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import java.util.concurrent.ExecutionException;

import fyp.spedmew.backend.entity.userEndpoint.model.User;
import fyp.spedmew.category.UserType;
import fyp.spedmew.connector.UserFindByNameATask;
import fyp.spedmew.connector.UserRegistrationATask;
import fyp.spedmew.util.Login;
import fyp.spedmew.util.Utility;
import fyp.spedmew.util.Validator;

public class MainActivityActionBarActivity extends ActionBarActivity {

    private User user = null;
    private ViewPager viewPager = null;
    private static final String TAG = new Object(){}.getClass().getCanonicalName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        user = new User(); // Create User object
        viewPager = (ViewPager) findViewById(R.id.pager);
        FragmentManager fm = getSupportFragmentManager();
        viewPager.setAdapter(new MyAdapter(fm));
    }

    class MyAdapter extends FragmentPagerAdapter
    {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            Fragment f = null;

            switch(i) {
                case 0:
                    f = new LoginPageFragment();
                    break;
                case 1:
                    f = new RegisterPageFragment();
                    break;
            }

            return f;
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {

            if(position == 0)
            {
                return "Sign-in";
            }
            else if(position == 1)
            {
                return "Register";
            }
            else
                return null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void onRadioButtonClicked(View view) {

        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.radioUser:
                if (checked)
                    user.setType(UserType.USER);
                    break;
            case R.id.radioDispatcher:
                if (checked)
                    user.setType(UserType.DISPATCHER);
                    break;
        }
    }

    public void loginMessage(View view)
    {
        final Button btn = (Button) findViewById(R.id.sign_in_btn);
        btn.setBackgroundColor(getResources().getColor(R.color.button_BG_OnPressed));

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                btn.setBackgroundColor(getResources().getColor(R.color.button_BG));
            }
        }, 300);

        DialogFragment dialog = new LoginErrorDialogFragment();
        FragmentManager fm = getSupportFragmentManager();

        EditText email_ET = (EditText) findViewById(R.id.email );
        EditText password_ET = (EditText) findViewById(R.id.password );

        String userName = email_ET.getText().toString();
        String password = password_ET.getText().toString();
        email_ET.setText("");
        password_ET.setText("");
        password = Utility.getHash(password);
        Intent out;

        User user = null;

        try {
            user = new UserFindByNameATask().execute(userName).get();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        if(user == null) {
            dialog.show(fm, "Tag");
        }
        else if(password.equals(user.getPassword())) {
            Login.setUser(user);
            if(user.getType().equals("USER")) {
                out = new Intent(this, UserListActionBarActivity.class);
                startActivity(out);
            }
            else if(user.getType().equals("DISPATCHER"))
            {
                out = new Intent(this, ListViewBaseActionBarActivity.class);
                startActivity(out);
            }
        }
        else {
            dialog.show(fm, "Tag");
        }

//        if (email.equalsIgnoreCase("a") && password.equals("a")) {
//            out = new Intent(this, UserListActionBarActivity.class);
//            startActivity(out);
//        }
//        else if (email.equalsIgnoreCase("user") && password.equals("user")){
//            out = new Intent(this, UserListActionBarActivity.class);
//            startActivity(out);
//        }else if (email.equalsIgnoreCase("d") && password.equals("d")) {
//            out = new Intent(this, ListViewBaseActionBarActivity.class);
//            startActivity(out);
//        }else {
//            dialog.show(fm, "Tag");
//        }
    }

    public void registerMessage(View view) throws ExecutionException, InterruptedException {

        final Button btn = (Button) findViewById(R.id.register_btn);
        btn.setBackgroundColor(getResources().getColor(R.color.button_BG_OnPressed));

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                btn.setBackgroundColor(getResources().getColor(R.color.button_BG));
            }
        }, 300);

        DialogFragment dialog = new RegisterOkDialogFragment();
        FragmentManager fm = getSupportFragmentManager();

        // Define toast setting
        Context context = getApplicationContext();
        CharSequence text;
        int duration = Toast.LENGTH_LONG;
        Toast toast;

        // Get references to EditText views
        EditText regEmail_ET = (EditText) findViewById(R.id.regEmail);
        EditText regPhone_ET = (EditText) findViewById(R.id.regPhone);
        EditText regPassword_ET = (EditText) findViewById(R.id.regPassword);
        EditText confirm_pw_ET = (EditText) findViewById(R.id.confirm_pw);

        // Get inputs from EditTexts
        String regEmail = regEmail_ET.getText().toString();
        String regPhone = regPhone_ET.getText().toString();
        String regPassword = regPassword_ET.getText().toString();
        String confirm_pw = confirm_pw_ET.getText().toString();

        if(regPassword.equals(confirm_pw)) {
            user.setName(regEmail);
            user.setPhone(regPhone);
            user.setPassword(regPassword);

            switch(Validator.checkUser(user)) {
                case 'P':
                    user.setPassword(Utility.getHash(regPassword));
                    String result = new UserRegistrationATask().execute(user).get();
                    if (result.equals(UserRegistrationATask.USER_EXIST)) {
                        text = "Username already exists. Please choose a different username";
                        toast = Toast.makeText(context, text, duration);
                        toast.show();
                    } else if (result.equals(UserRegistrationATask.OK)) {
                        dialog.show(fm, "Tag");
                    }
                    Log.i(TAG, "User registration called. Result " + result);
                    break;

                case 'A':   text = "Username is invalid";
                            toast = Toast.makeText(context, text, duration);
                            toast.show();
                            break;

                case 'B':   text = "Please enter contact number";
                            toast = Toast.makeText(context, text, duration);
                            toast.show();
                            break;

                case 'C':   text = "Password doesn't meet policy requirements";
                            toast = Toast.makeText(context, text, duration);
                            toast.show();
                            break;

                case 'D':   text = "Please select a user type";
                            toast = Toast.makeText(context, text, duration);
                            toast.show();
                            break;
                }
        } else {
            text = "Passwords doesn't match";
            toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    }
}
